package gb

import (
	"bytes"
	"github.com/ghettovoice/gosip/sip"
	log "github.com/sirupsen/logrus"
	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
	"io"
	"net/http"
)

func gbkToUtf8(s []byte) ([]byte, error) {
	reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewDecoder())
	buffer := bytes.Buffer{}
	_, err := buffer.ReadFrom(reader)
	if err != nil {
		return nil, err
	}
	return buffer.Bytes(), nil
}

func responseAck(transaction sip.ServerTransaction, request sip.Request) error {
	err := transaction.Respond(sip.NewResponseFromRequest("", request, sip.StatusCode(http.StatusOK),
		http.StatusText(http.StatusOK), ""))
	if err != nil {
		log.Error(err)
		return err
	}
	return nil
}

func response100(transaction sip.ServerTransaction, request sip.Request) error {
	err := transaction.Respond(sip.NewResponseFromRequest("", request, sip.StatusCode(http.StatusContinue),
		http.StatusText(http.StatusContinue), ""))
	if err != nil {
		log.Error(err)
		return err
	}
	return nil
}
func gb2312CharsetReader(charset string, input io.Reader) (io.Reader, error) {
	if charset == "GB2312" {
		return transform.NewReader(input, simplifiedchinese.GB18030.NewDecoder()), nil
	}
	return input, nil
}
